package com.game;

import java.io.FileInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ZZClientServerConfigXmlLoader {
	private Logger log = Logger.getLogger(ZZClientServerConfigXmlLoader.class);

	public ZZClientServerConfig load(String file) {
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			InputStream in = new FileInputStream(file);
			Document doc = builder.parse(in);
			NodeList list = doc.getElementsByTagName("server");

			ZZClientServerConfig config = new ZZClientServerConfig();
			if (list.getLength() > 0) {
				Node node = list.item(0);
				NodeList childs = node.getChildNodes();

				for (int j = 0; j < childs.getLength(); j++) {
					if ("connect-servers".equals(childs.item(j).getNodeName())) {
						NodeList servers = childs.item(j).getChildNodes();
						for (int k = 0; k < servers.getLength(); k++) {
							if ("connect-server".equals(servers.item(k).getNodeName())) {
								Node line = servers.item(k);
								ZZServerInfo info = new ZZServerInfo();
								NodeList attrs = line.getChildNodes();
								for (int l = 0; l < attrs.getLength(); l++) {
									if ("server-id".equals(attrs.item(l).getNodeName()))
										info.setId(Integer.parseInt(attrs.item(l).getTextContent().trim()));
									else if ("server-ip".equals(attrs.item(l).getNodeName()))
										info.setIp(attrs.item(l).getTextContent().trim());
									else if ("server-port".equals(attrs.item(l).getNodeName()))
										info.setPort(Integer.parseInt(attrs.item(l).getTextContent().trim()));
									else if ("server-type".equals(attrs.item(l).getNodeName()))
										info.setType(attrs.item(l).getTextContent().trim());
									else if ("server-name".equals(attrs.item(l).getNodeName()))
										info.setName(attrs.item(l).getTextContent().trim());
									else if ("server-plat".equals(attrs.item(l).getNodeName()))
										info.setPlat(attrs.item(l).getTextContent().trim());
								}
								config.getConnectServers().add(info);
							}
						}
					}
				}
			}
			in.close();
			return config;
		} catch (Exception e) {
			this.log.error(e, e);
		}
		return null;
	}
}
